﻿/*! @file
********************************************************************************
<PRE>
文件名       : FrmRegister.cs
作者         : 汪泽然
--------------------------------------------------------------------------------
备注         : 主界面，添加/删除右键菜单
--------------------------------------------------------------------------------
修改记录 : 
 * 日 期            版本         修改人           修改内容 
 * 2008-5-29        0.1.0        汪泽然           创建
 * 2008-6-4         0.2.0        汪泽然           精简了重复的代码
 * 2008-6-7         0.2.1        汪泽然           修复了读取版本的Bug
 * 2008-6-14        0.3.0        汪泽然           重新设计UI，并增加了扩展功能
 * 2008-6-15        0.3.6        汪泽然           完成解决方案文件的个版本转换
 * 2008-6-17        0.3.9        汪泽然           将转换结果写为日志文件，转换结束后打开该日志文件
 * 2008-6-18        0.4.0        汪泽然           项目测试OK！
 * 2008-9-25        0.4.3        汪泽然           修复文件名检测的Bug
 * 2008-9-26        0.4.5        汪泽然           添加到右键菜单，选中解决方案文件即可转换
 * 2008-9-27        0.4.6        汪泽然           修改添加到注册表的位置(Failure)
 * 2008-9-28        0.4.6        汪泽然           添加到右键一级菜单
 * 2009-6-18        0.4.7        汪泽然           添加对ASP.NET项目的转换
 * 2009-6-22        0.4.9        汪泽然           增加转换失败时的备份/还原机制
 * 2009-6-23        0.4.11       汪泽然           增加对是否添加到右键的检测
 * 2009-7-5         0.4.13       汪泽然           封装消息到资源文件
 * 2009-7-11        0.5.0        汪泽然           增加“关于”信息，显示插件的提供者
 *                                                增加移开时半透明效果
 * 2009-7-16        0.5.1        汪泽然           完善插件信息
</PRE>
********************************************************************************
* 版权所有(c) 2008, 汪泽然, 保留所有权利
*******************************************************************************/
using System;
using System.Drawing;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using Wangzeran.Transform.Code;
using Wangzeran.Transform.Core.PlugIn;
using Wangzeran.Transform.Resources;
using Wangzeran.Transform.Util;
using Wangzeran.Transform.Core.TransformException;
using System.Threading;
using System.IO;

namespace Wangzeran.Transform.Forms
{
    /// <summary>
    /// 添加到注册表的页面
    /// </summary>
    public partial class RegisterFrm : Form
    {
        /// <summary>
        /// 注册表的项名称
        /// </summary>
        const string REG_VSTRANSLATE = "VSTransform.sln";
        /// <summary>
        /// 注册表的VisualStudio.Launcher.sln
        /// </summary>
        const string VS_LAUNCHER_SLN = "VisualStudio.Launcher.sln";


        #region StringBuilders

        /// <summary>
        /// 更新日志
        /// </summary>
        private StringBuilder sbUploadLog = null;

        /// <summary>
        /// 关于
        /// </summary>
        private StringBuilder sbAbout = null;

        #endregion


        public RegisterFrm()
        {
            InitializeComponent();

            // 启动界面透明检测的定时器
            timerOpacity.Start();
        }


        /// <summary>
        /// 启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FrmRegister_Load(object sender, EventArgs e)
        {
            this.Text = AppResource.AppName + "  " + 
                AppResource.AppVersion;

            CheckAddRegister();

            ShowPlugIns();
        }

        /// <summary>
        /// 添加右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddRegister_Click(object sender, EventArgs e)
        {
            try
            {
                #region Version 1.0

                //RegistryKey root = Registry.ClassesRoot;
                //RegistryKey application = root.OpenSubKey("Applications", true);
                //try
                //{
                //    application.DeleteSubKeyTree("Translate.exe");
                //}
                //catch
                //{ }

                //RegistryKey translate = application.CreateSubKey("Translate.exe");
                //RegistryKey shell = translate.CreateSubKey("Shell");
                //RegistryKey open = shell.CreateSubKey("Open");
                //RegistryKey command = open.CreateSubKey("Command");

                //string filepath = Assembly.GetExecutingAssembly().Location;

                //command.SetValue("", "\"" + filepath + "\" \"%1\"");


                //RegistryKey sln = root.OpenSubKey(".sln", true);
                //RegistryKey openWithlist = sln.CreateSubKey("OpenWithList");
                //try
                //{
                //    openWithlist.DeleteSubKey("Translate.exe");
                //}
                //catch
                //{}
                //openWithlist.CreateSubKey("Translate.exe");

                #endregion
                
                #region Version 2.0

                RegistryKey root = Registry.ClassesRoot;
                RegistryKey vslauncher = root.OpenSubKey(VS_LAUNCHER_SLN, true);
                RegistryKey shell = vslauncher.OpenSubKey("Shell", true);
                RegistryKey vsTranlate = shell.CreateSubKey(AppResource.RegisterName);
                RegistryKey command = vsTranlate.CreateSubKey("Command");

                string filepath = Assembly.GetExecutingAssembly().Location;

                command.SetValue("", "\"" + filepath + "\" \"%1\"");
                command.Close();

                root.Close();

                #endregion

                CheckAddRegister();

                MessageUtil.ShowInformation(MessageResource.ADD_REG_SUCCESS);

            }
            catch (UnauthorizedAccessException)
            {
                MessageUtil.ShowError(MessageResource.REG_ACCESS_INVALID);
            }
            catch (Exception ex)
            {
                MessageUtil.ShowError(MessageResource.ADD_REG_FAILED + ex.Message);
            }            
        }

        /// <summary>
        /// 移除右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemoveRegister_Click(object sender, EventArgs e)
        {
            try
            {
                #region Version 1.0

                //RegistryKey root = Registry.ClassesRoot;
                //RegistryKey application = root.OpenSubKey("Applications", true);
                //application.DeleteSubKeyTree("Translate.exe");

                //RegistryKey sln = root.OpenSubKey(".sln", true);
                //RegistryKey openWithlist = sln.CreateSubKey("OpenWithList");
                //openWithlist.DeleteSubKeyTree("Translate.exe");

                #endregion

                #region Version 2.0

                RegistryKey root = Registry.ClassesRoot;
                RegistryKey vslauncher = root.OpenSubKey(VS_LAUNCHER_SLN, true);
                RegistryKey shell = vslauncher.OpenSubKey("Shell", true);
                shell.DeleteSubKeyTree(AppResource.RegisterName);
                root.Close();

                #endregion

                CheckAddRegister();

                MessageUtil.ShowInformation(MessageResource.REMOVE_REG_SUCCESS);
            }
            catch (UnauthorizedAccessException)
            {
                MessageUtil.ShowError(MessageResource.REG_ACCESS_INVALID);
            }
            catch (ArgumentException)
            {
                MessageUtil.ShowError(MessageResource.ADD_REG_UNADD);
            }
            catch (Exception ex)
            {
                MessageUtil.ShowError(MessageResource.REMOVE_REG_FAILED + ex.Message);
            }
        }

        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.ExitThread();
        }

        /// <summary>
        /// 显示更新日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUpdateLog_Click(object sender, EventArgs e)
        {
            if (sbUploadLog == null)
            {
                sbUploadLog = new StringBuilder();
                sbUploadLog.AppendLine(AppResource.UpdateLog);
                sbUploadLog.AppendLine();
                sbUploadLog.AppendLine("Transform.Core更新日志：");
                sbUploadLog.AppendLine(Transform.Core.Resources.AppResource.UpdateLog);
            }
            ShowMessagePanel(AppResource.UpdateLogName, sbUploadLog.ToString(), Color.FromArgb(255, 128, 0));
        }

        /// <summary>
        /// 显示关于信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAbout_Click(object sender, EventArgs e)
        {
            if (sbAbout == null)
            {
                try
                {
                    sbAbout = new StringBuilder();
                    sbAbout.AppendLine(AppResource.AppName + " " + AppResource.AppVersion);
                    sbAbout.AppendLine();
                    sbAbout.AppendLine("编译工具：");
                    sbAbout.AppendLine(AppResource.CompilerTools);
                    sbAbout.AppendLine(AppResource.CompilerFramework);
                    sbAbout.AppendLine();
                    sbAbout.AppendLine("软件参与者：");
                    sbAbout.AppendLine(AppResource.Participants);
                    sbAbout.AppendLine();
                    sbAbout.AppendLine("插件信息：");
                    if (PlugIns.RegisterPlugIns.Count == 0)
                    {
                        throw new InvalidPlugInException();
                    }
                    foreach (IPlugInInfo item in PlugIns.RegisterPlugIns.Values)
                    {
                        sbAbout.AppendLine("感谢  " + item.Author);
                        sbAbout.AppendLine("提供  " + item.TargetIDEVersion + "  的转换插件");
                        sbAbout.AppendLine("目标语言：" + item.TargetLanguage);
                        sbAbout.AppendLine("目标框架：" + item.TargetFrameworkVersion);
                        sbAbout.AppendLine("插件版本：" + item.PlugInVersion);
                        sbAbout.AppendLine("更新日志：");
                        sbAbout.AppendLine(item.UpdateLog);
                        sbAbout.AppendLine();
                    }
                }
                catch (BaseException)
                {
                    sbAbout.AppendLine("暂无插件信息");
                    sbAbout.AppendLine();
                }
            }
            ShowMessagePanel(AppResource.About, sbAbout.ToString(), Color.FromArgb(002, 002, 123));

        }

        /// <summary>
        /// 初始化插件
        /// </summary>
        private void InitPlugIns()
        {
            try
            {
                if (!Directory.Exists("PlugIns"))
                {
                    Directory.CreateDirectory("PlugIns");
                    throw new InvalidPlugInException();
                }
                if (PlugIns.RegisterPlugIns.Count == 0)
                {
                    throw new InvalidPlugInException();
                }
                foreach (IPlugInInfo plugIn in PlugIns.RegisterPlugIns.Values)
                {
                    ListViewItem item = new ListViewItem();
                    item.Text = plugIn.TargetIDEVersion + "【" + plugIn.TargetLanguage + "】";
                    item.ImageIndex = 0;
                    lstPlugIns.Items.Add(item);
                }
            }
            catch (BaseException)
            {
                ListViewItem item = new ListViewItem("未检测到任何插件");
                item.ImageIndex = 1;
                lstPlugIns.Items.Add(item);
            }
        }

        /// <summary>
        /// 显示已检测的插件
        /// </summary>
        private void ShowPlugIns()
        {
            if (lstPlugIns.Items.Count == 0)
            {
                InitPlugIns();
            }
            ShowMessagePanel("插件", "", Color.Green);
            txtMessage.Visible = false;
            lstPlugIns.Visible = true;
        }

        /// <summary>
        /// 显示信息框
        /// </summary>
        /// <param name="title">信息标题</param>
        /// <param name="content">信息内容</param>
        /// <param name="color">文本颜色</param>
        private void ShowMessagePanel(string title, string content, Color color)
        {
            if (gbMessage.Visible && gbMessage.Text == title)
            {
                txtMessage.Visible = false;
                ShowPlugIns();
                return;
            }

            gbMessage.Text = title;
            txtMessage.ForeColor = color;
            txtMessage.Text = content;

            lstPlugIns.Visible = false;
            txtMessage.Visible = true;
            

        }


        /// <summary>
        /// 检测注册表，检查是否已添加至右键菜单
        /// </summary>
        private void CheckAddRegister()
        {
            try
            {
                RegistryKey root = Registry.ClassesRoot;
                RegistryKey vslauncher = root.OpenSubKey(VS_LAUNCHER_SLN, true);
                RegistryKey shell = vslauncher.OpenSubKey("Shell", true);
                RegistryKey vsTranlate = shell.OpenSubKey(AppResource.RegisterName);
                RegistryKey command = vsTranlate.OpenSubKey("Command");

                string regFilepath = command.GetValue("").ToString();
                string filepath = "\"" + Assembly.GetExecutingAssembly().Location + "\" \"%1\"";

                if (regFilepath == filepath)
                {
                    lblRegisterState.Text = MessageResource.LABEL_ADD_REG;
                    lblRegisterState.ForeColor = Color.Green;
                    btnAddRegister.Enabled = false;
                    btnRemoveRegister.Enabled = true;
                }
                else
                {
                    throw new Exception();
                }
            }
            catch
            {
                lblRegisterState.Text = MessageResource.LABEL_UNADD_REG;
                lblRegisterState.ForeColor = Color.Red;
                btnRemoveRegister.Enabled = false;
                btnAddRegister.Enabled = true;
            }
        }

        /// <summary>
        /// 透明检测的定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerOpacity_Tick(object sender, EventArgs e)
        {
            CheckMouseUpForm();
        }

        /// <summary>
        /// 检查鼠标是否在窗体上，是的话就设置为不透明，否则设为半透明
        /// </summary>
        private void CheckMouseUpForm()
        {
            Point frmPoint = this.Location;
            Point mousePoint = MousePosition;

            if (mousePoint.X > frmPoint.X
                && mousePoint.X < (frmPoint.X + this.Width)
                && mousePoint.Y > frmPoint.Y
                && mousePoint.Y < (frmPoint.Y + this.Height))
            {
                if (this.Opacity != 1)
                {
                    this.Opacity = 1;
                }
            }
            else
            {
                if (this.Opacity == 1)
                {
                    this.Opacity = 0.6;
                }
            }
        }

        /// <summary>
        /// 显示使用说明
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbtnShowHelp_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            ShowMessagePanel("使用说明", AppResource.HELP, Color.Black);
        }

    }
}
